﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using ShopB2C.Entity;
using ShopB2C.Enums;
using ShopB2C.ViewModels;
using Valor.Helper;
using Valor.Helpr.Enums;
using xTeam.HengLe.Entity;

namespace xTeam.HengLe.Controller.Website
{
    public class ShopCarController : BaseController
    {

        public ActionResult Index()
        {
            return RedirectToAction("ShopCar");
        }

        protected override void Initialize(System.Web.Routing.RequestContext requestContext)
        {
            base.Initialize(requestContext);
            //合并购物车
            if (User.Identity.IsAuthenticated)
                this.MergeShopCar();
        }


        public ActionResult ShopCar()
        {
            this.SiteMapPathAdd(ViewsResources.SiteMapPath.ShopCar);

            ShopCarViewModel _viewMode = new ShopCarViewModel() { ImageRoot = _imageRoot };
            _viewMode.CarList = User.Identity.IsAuthenticated
                ? _shopCarAccess.CarList(_user.Uid, (int)ShopCarType.ShopCar)
                : GetCookCar();

            return View(_viewMode);
        }
        /// <summary>
        /// 增加到购物车
        /// </summary>
        [HttpPost]
        public ActionResult AddToCar(
            [DefaultValue(0)]int productId
            , [DefaultValue(1)]int count)
        {
            MessageHelper msg = new MessageHelper("shopcar");
            msg.AddBody(4);
            msg.DefaultOperate("javascript:CloseDialog()");
            // 从cookie中获取购物车
            List<EProduct> cookieCar = GetCookCar();
            // 参数检查
            if (productId > 0)
            {
                // 附加可选参数
                string optional = string.Empty;
                if (Request.Form["optional"] != null)
                {
                    //对参选进行排序，以防止管理员调整了参数排序属性错乱
                    var optionals = Request.Form.GetValues("optional").OrderBy(i => Convert.ToInt32(i));
                    foreach (string i in optionals)
                    {
                        optional += string.Format("{0},", i);
                    }
                    optional = optional.Trim(',');
                }

                if (!User.Identity.IsAuthenticated)
                {
                    #region 查找元素在列表中的索引

                    int index = -1;
                    var c = cookieCar.Where((item, innerIndex) =>
                    {
                        if (item.ProductId == productId && item.KeyWords == optional)// 提示信息:用户自定属性存放于KeyWords
                        {
                            index = innerIndex;
                            return true;
                        }
                        else
                        {
                            return false;
                        }
                    }).FirstOrDefault();

                    if (c != null)
                    {
                        cookieCar[index].SalesCount += count;
                    }
                    else
                    {
                        //  cookie中没有发现产品增加该产品
                        cookieCar.Add(new EProduct()
                        {
                            ProductId = productId,
                            SalesCount = count,
                            KeyWords = optional, // 提示信息:用户自定属性存放于KeyWords
                        });
                    }

                    #endregion

                    this.WriteCookCar(cookieCar);
                }
                else
                {
                    int result = _shopCarAccess.AddToCar(new ShopCarEntity()
                    {
                        Uid = _user.Uid,
                        ProductId = productId,
                        Property = optional,
                        Count = count,
                        Description = "",
                        CartType = (int)ShopCarType.ShopCar
                    });
                }

                msg.AddOperate("查看购物车", Url.Action("ShopCar", "ShopCar"));
                msg.AddMessage(4);
            }
            else
            {
                msg.AddBody(3);
                msg.AddMessage(5);
            }
            return MessageResult(msg.CreateMessage(), ResultType.AjaxHtml);
        }
        /// <summary>
        /// 保存购物车
        /// </summary>
        [HttpPost]
        public ActionResult ShopCar([DefaultValue("")]string setpNext)
        {
            if (Request.Form["ProductId"] != null)
            {
                string[] ids = Request.Form.GetValues("ProductId");
                string[] counts = Request.Form.GetValues("Count");
                // 提示，这里加入自选属性是因为购物车并没有主键，因此进行修改删除的时候需要同时提供ID和可选属性
                string[] optionals = Request.Form.GetValues("optional");

                List<EProduct> cookieCar = GetCookCar();

                for (int i = 0; i < ids.Length; i++)
                {
                    int productId, count;
                    int.TryParse(ids[i], out productId);
                    int.TryParse(counts[i], out count);

                    // 参数检查
                    if (productId <= 0)
                        break;


                    if (!User.Identity.IsAuthenticated)
                    {


                        #region 查找元素在列表中的索引

                        int index = -1;
                        var c = cookieCar.Where((item, innerIndex) =>
                        {
                            if (item.ProductId == productId && item.KeyWords == optionals[i])// 提示性说明，用户自定义属性存放于KeyWords
                            {
                                index = innerIndex;
                                return true;
                            }
                            else
                            {
                                return false;
                            }
                        }).FirstOrDefault();

                        if (c != null)
                        {
                            cookieCar[index].SalesCount = count;
                            // 购买数量为0时从购物车删除
                            if (count < 1)
                                cookieCar.RemoveAt(index);
                        }
                        #endregion

                        this.WriteCookCar(cookieCar);

                    }
                    else
                    {

                        _shopCarAccess.UpdateCar(
                          productId
                           , count
                           , optionals[i]
                           , _user.Uid
                           , (int)ShopCarType.ShopCar
                           );
                    }

                }
            }
            return !string.IsNullOrEmpty(setpNext)
                ? RedirectToAction("OrderPreview","Customer",null)
                : RedirectToAction("ShopCar");

        }
        /// <summary>
        /// 删除购物车
        /// </summary>
        [HttpPost]
        public ActionResult DeleteCarItem(
            [DefaultValue(0)]int productId
            , [DefaultValue("")]string optional/* 提示，这里加入自选属性是因为购物车并没有主键，因此进行修改删除的时候需要同时提供ID和可选属性*/)
        {

            if (User.Identity.IsAuthenticated)
            {
                int result = _shopCarAccess.DeleteCar(productId, optional, _user.Uid, (int)ShopCarType.ShopCar);
            }
            else
            {

                #region 查找元素在列表中的索引

                List<EProduct> cookieCar = GetCookCar();
                int index = -1;
                var c = cookieCar.Where((item, innerIndex) =>
                {
                    // 购物车提示信息：用自定义属性存放于KeyWords属性
                    if (item.ProductId == productId && item.KeyWords == optional)
                    {
                        index = innerIndex;
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }).FirstOrDefault();

                if (c != null)
                {
                    cookieCar.RemoveAt(index);
                }

                #endregion

                // 写入cookie
                this.WriteCookCar(cookieCar);
            }
            return new EmptyResult();
        }

        /// <summary>
        /// 关联收货人地址
        /// </summary>
        [Authorize()]
        public ActionResult ShopCar2()
        {
            this.SiteMapPathAdd(ViewsResources.SiteMapPath.ShopCar, Url.Action("ShopCar", "ShopCar"));
            this.SiteMapPathAdd(ViewsResources.SiteMapPath.DeliveryAddress);

            CustomerViewModel _viewModel = new CustomerViewModel();
            _viewModel.AddressBookList = _userAccess.AddressBookList(_user.Uid);
            return View(_viewModel);
        }
        [HttpPost]
        [Authorize]
        public ActionResult AddToOrder(
            UserAddressEntity shipAddress)
        {
            // 收货地址正确性检查
            MessageHelper msg = new MessageHelper("shopcar");
            msg.AddBody(1);
            msg.Required(shipAddress.ReallyName, 1);
            msg.Required(shipAddress.Address, 2);
            if (msg.IsValid)
            {
                shipAddress.Uid = _user.Uid;
                _userAccess.SaveAddressBook(shipAddress);
                //转到真正的增加订单
                return RedirectToAction("AddToOrder", "Customer", new { addressId = shipAddress.AddressId });
            }
            return MessageResult(msg.CreateMessage());
        }
        private void MergeShopCar()
        {
            List<EProduct> cookieCar = GetCookCar();
            foreach (EProduct item in cookieCar)
            {
                int result = _shopCarAccess.AddToCar(new ShopCarEntity()
                {
                    Uid = _user.Uid,
                    ProductId = item.ProductId,
                    Count = item.SalesCount,
                    Property = item.KeyWords,//核心提示，用户自定义属性存放在KeyWords里面
                    Description = "",
                    CartType = (int)ShopCarType.ShopCar
                });
            }
            Response.Cookies.Add(new HttpCookie(string.Format("{0}_{1}", _shopCarCookieName, _langName)) { Expires = DateTime.Now.AddDays(-1) });
        }
        /// <summary>
        /// 从cookie中反向存储的购物车数据
        /// </summary>
        /// <returns></returns>
        private List<EProduct> GetCookCar()
        {
            List<CookieCarEntity> carCookie;
            try
            {
                JavaScriptSerializer json = new JavaScriptSerializer();
                carCookie = json.Deserialize<List<CookieCarEntity>>(
                    Request.Cookies[string.Format("{0}_{1}", _shopCarCookieName, _langName)] != null
                    ? Request.Cookies[string.Format("{0}_{1}", _shopCarCookieName, _langName)].Value
                    : string.Empty)
                    ?? new List<CookieCarEntity>();
            }
            catch
            {
                carCookie = new List<CookieCarEntity>();
            }

            List<EProduct> cookieCar = new List<EProduct>();
            foreach (CookieCarEntity item in carCookie)
            {
                EProduct product = _shopCarAccess.GetProductByCookId(item.ProductId, item.Property, (int)ShopCarType.ShopCar);
                if (product != null)
                {
                    product.SalesCount = item.Count;
                    cookieCar.Add(product);
                }
            }

            return cookieCar;
        }
        /// <summary>
        /// 将修正的购物车写入Cookie
        /// </summary>
        private void WriteCookCar(List<EProduct> cookieCar)
        {
            // 在新开一个Entity是因为他的属性少
            List<CookieCarEntity> carCookie = new List<CookieCarEntity>();
            foreach (EProduct item in cookieCar)
            {
                carCookie.Add(new CookieCarEntity()
                {
                    ProductId = item.ProductId,
                    Count = item.SalesCount,
                    Property = item.KeyWords // 购物车提示信息：用自定义属性存放于KeyWords属性
                });
            }

            JavaScriptSerializer json = new JavaScriptSerializer();

            Response.Cookies.Add(new HttpCookie(string.Format("{0}_{1}", _shopCarCookieName, _langName))
            {
                Value = json.Serialize(carCookie),
                Expires = DateTime.Now.AddDays(6)
            });
        }
    }
}
